package com.itphy.service.Impl;

import com.alibaba.fastjson.JSON;
import com.itphy.common.HttpURLConnectionUtil;
import com.itphy.common.wechat.TemplateMessage;
import com.itphy.common.wechat.WechatEnum;
import com.itphy.service.WechatService;
import com.itphy.util.RedisClient;
import org.apache.commons.lang3.StringUtils;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class WechatServiceImpl implements WechatService {
    @Inject("${wechat.app_id}")
    private String app_id;
    @Inject("${wechat.app_secret}")
    private String app_secret;

    @Override
    public String getAccessToken() {
        try {
            String accessToken = RedisClient.getJedis().get("ACCESS_TOKEN");
            if(StringUtils.isEmpty(accessToken)){
                String result = HttpURLConnectionUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+app_id+"&secret="+app_secret);
                Map<String,Object> data = JSON.parseObject(result, Map.class);
                if(!Objects.isNull(data.get("access_token"))){
                    RedisClient.getJedis().setex("ACCESS_TOKEN", Integer.parseInt(data.get("expires_in").toString()),data.get("access_token").toString());
                    return data.get("access_token").toString();
                }
            }
            return accessToken;
        }catch (Exception e){
            throw new RuntimeException("access_token 获取失败");
        }
    }

    @Override
    public boolean sendTemplateMessage(TemplateMessage message) {
        String result=HttpURLConnectionUtil.doPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" +getAccessToken(), message.toString());
        Map<String,Object> map = JSON.parseObject(result, Map.class);
        if(!Objects.isNull(map.get("errcode"))){
            if(!"0".equals(map.get("errcode").toString())){
                throw new RuntimeException("消息发送失败"+map.get("errmsg"));
            }
            return true;
        }
        return false;
    }
}
